# 新增：导入环境配置和应用标识
from config.default import APP_CODE  # 从config/default.py导入APP_CODE
from django.conf import settings  # 从Django配置中获取ENVIRONMENT（假设ENVIRONMENT在settings中定义）

from .models import WeChatUser, Status
from django.shortcuts import redirect, render


def home(request):
    return render(request, 'homepage.html')


def show_user(request):
    user_id = request.user.id
    wechat_user = WeChatUser.objects.get(user_id=user_id)
    return render(request, 'user.html', {'user': wechat_user})


def show_status(request):
    statuses = Status.objects.all()
    return render(request, 'status.html', {'statuses': statuses})


def submit_post(request):
    # 修复1：添加异常处理，避免用户不存在时崩溃
    try:
        # 注意：如果WeChatUser关联的是user对象，用request.user；如果是user_id，用request.user.id
        user = WeChatUser.objects.get(user=request.user)  # 或 user_id=request.user.id，根据你的模型字段调整
    except WeChatUser.DoesNotExist:
        return render(request, 'my_post.html', {'error': '请先创建用户'})

    text = request.POST.get('text')
    if text:
        status = Status(user=user, text=text)
        status.save()
        # 修复2：根据环境动态调整重定向路径
        if settings.ENVIRONMENT == 'dev':  # 开发环境
            return redirect('/status')
        elif settings.ENVIRONMENT == 'stag':  # 预发布环境
            return redirect(f'/stag--{APP_CODE}/status')
    return render(request, 'my_post.html')